package com.ls.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.product.model.AddProductModel;
import com.ls.controller.product.model.EditProductModel;
import com.ls.controller.product.model.updateStatusModel;
import com.ls.entity.*;
import com.ls.enums.RoleEnum;
import com.ls.mapper.OrderRecordMapper;
import com.ls.mapper.ProductMapper;
import com.ls.service.IProductService;
import com.ls.utils.ResultData;
import com.ls.utils.UUIDUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import static com.ls.constant.SystemConstants.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    private final OrderRecordMapper orderRecordMapper;

    /**
     * 生成订单编号
     */
    @Override
    public ResultData createOrderNum(Long productId) {
        Customer customer = SaTokenUtilPy.getCustomer();
        String coustomerId = String.valueOf(customer.getCustomerId());
        //获取当前的时间戳
        String Num = coustomerId + String.valueOf(System.currentTimeMillis());
        //判断当前用户是否已经生成了订单
        OrderRecord existingOrder = orderRecordMapper.selectOne(
                new LambdaQueryWrapper<OrderRecord>()
                        .eq(OrderRecord::getCustomerId, customer.getCustomerId())
                        .eq(OrderRecord::getOrderStatus, PAY_STATUS_WAIT)
        );
        OrderRecord lastRecord = null;
        //获取选择的套餐
        Product product = getById(productId);
        boolean flag = false;
        if (existingOrder != null) {
//            Num=Num+String.valueOf(existingOrder.getOrderRecordId());
            Num = existingOrder.getOrderNum();
            existingOrder.setOrderNum(Num);
            existingOrder.setUpdateTime(LocalDateTime.now());
            existingOrder.setProductId(productId);
            existingOrder.setProductType(product.getProductType());
            existingOrder.setPeriod(product.getPeriod());
            existingOrder.setFee(customer.getMemberStatus() == MEMBER_STATUS_TRUE ? product.getFee() : product.getCommonFee());
            existingOrder.setMonthSmsQuantity(product.getMonthSmsQuantity());
            flag = existingOrder.updateById();
        } else {
            //获取最后一条订单记录id
            lastRecord = orderRecordMapper.selectOne(
                    new LambdaQueryWrapper<OrderRecord>()
                            .orderByDesc(OrderRecord::getOrderRecordId)
                            .last("LIMIT 1")
            );
            Long lastOrderId = lastRecord != null ? lastRecord.getOrderRecordId() + 1 : 1L;
            Num = Num + String.valueOf(lastOrderId);
            OrderRecord orderRecord = new OrderRecord();
            orderRecord.setOrderNum(Num);
            orderRecord.setCustomerId(customer.getCustomerId());
            orderRecord.setPhone(customer.getPhone());
            orderRecord.setProductId(productId);
            orderRecord.setProductType(product.getProductType());
            orderRecord.setPeriod(product.getPeriod());
            orderRecord.setFee(customer.getMemberStatus() == MEMBER_STATUS_TRUE ? product.getFee() : product.getCommonFee());
            orderRecord.setMonthSmsQuantity(product.getMonthSmsQuantity());
            orderRecord.setOrderStatus(PAY_STATUS_WAIT);
            orderRecord.setCreateTime(LocalDateTime.now());
            orderRecord.setUpdateTime(LocalDateTime.now());
            orderRecord.setExpireType(NUMBER_0);
            flag = orderRecord.insert();
        }
        log.info("订单编号：{}", Num);
        log.info("生成订单编号长度：{}", Num.length());
        if (flag) {
            return ResultData.successData(Num);
        } else {
            return ResultData.failure("生成订单编号失败");
        }
    }

    /**
     * 新增套餐
     */
    @Override
    public ResultData add(AddProductModel model) {
        SysUser sysUser = SaTokenUtilPy.getSysUser();
        RoleEnum roleEnum = RoleEnum.getRoleEnum(sysUser.getRoleId());
        if (!RoleEnum.ADMIN.equals(roleEnum)) {
            return ResultData.failure("只有管理员才能新增套餐");
        }
        Product product = new Product();
        log.info("新增套餐：{}", model);
        BeanUtils.copyProperties(model, product);
        product.setValidFlag(NUMBER_1);
        product.setCreateTime(LocalDateTime.now());
        product.setUpdateTime(LocalDateTime.now());
        product.setCreatorId(sysUser.getUserId());
        product.setUpdaterId(sysUser.getUserId());
        boolean flag = save(product);
        if (flag) {
            return ResultData.successMsg("新增成功");
        } else {
            return ResultData.failure("新增失败");
        }
    }

    /**
     * 编辑套餐
     */
    @Override
    public ResultData edit(EditProductModel model) {
        SysUser sysUser = SaTokenUtilPy.getSysUser();
        RoleEnum roleEnum = RoleEnum.getRoleEnum(sysUser.getRoleId());
        if (!RoleEnum.ADMIN.equals(roleEnum)) {
            return ResultData.failure("只有管理员才能修改套餐");
        }
        //获取当前轮播图id判断是否存在
        Product product = getById(model.getProductId());
        if (product == null) {
            return ResultData.failure("轮播图不存在");
        }
        //实现修改轮播图
        BeanUtils.copyProperties(model, product);
        product.setUpdaterId(sysUser.getUserId());
        boolean flag = updateById(product);
        if (flag) {
            return ResultData.successMsg("修改成功");
        } else {
            return ResultData.failure("修改失败");
        }
    }

    /**
     * 查询套餐列表
     */
    @Override
    public ResultData getProduct(Integer productType) {
//        if (productType==null){
//            return ResultData.successData(list(new LambdaQueryWrapper<Product>().eq(productType!=null,Product::getProductType, productType)
//                    .groupBy(Product::getCreateTime).orderByDesc(Product::getCreateTime)
//            ));
//        }
//        if(productType==PRODUCT_TYPE_MEMBER){
//            Customer customer = SaTokenUtilPy.getCustomer();
//            // 修改后的完整逻辑
//            List<Product> productList = list(new LambdaQueryWrapper<Product>()
//                    .eq(Product::getProductType, productType)
//                    .groupBy(Product::getCreateTime)
//                    .orderByAsc(Product::getMonthSmsQuantity)
//            );
//            // 新增费用替换逻辑
//            if (customer.getMemberStatus() != MEMBER_STATUS_TRUE) {
//                productList.forEach(p -> p.setFee(p.getCommonFee()));
//            }
//
//            return ResultData.successData(productList);
//
//        }
//        if(productType==PRODUCT_TYPE_SMS){
//            Customer customer = SaTokenUtilPy.getCustomer();
//            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
//            log.info("会员状态：{}", customer.getMemberStatus());
//            log.info("会员到期时间：{}", customer.getSmsExpireTime());
//
//            if (customer.getMemberStatus() == MEMBER_STATUS_TRUE
//                    || customer.getSmsExpireTime()!=null&&customer.getSmsExpireTime().isAfter(LocalDateTime.now())) {
//                wrapper.in(Product::getProductType, PRODUCT_TYPE_SMS, PRODUCT_TYPE_SMS_ADDITION);
//            } else {
//                wrapper.eq(Product::getProductType, SMS_PACKAGE_STATUS_FALSE);
//            }
//
//            wrapper.groupBy(Product::getCreateTime)
//                    .orderByAsc(Product::getProductType)
//                    .orderByAsc(Product::getMonthSmsQuantity);
//
//            // 新增费用替换逻辑
//            List<Product> productList = list(wrapper);
//            if (customer.getMemberStatus() != MEMBER_STATUS_TRUE) {
//                productList.forEach(p -> p.setFee(p.getCommonFee()));
//            }
//
//            return ResultData.successData(productList);
//        }
//        return ResultData.success();

        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();

        if (productType != null) {
            Customer customer = SaTokenUtilPy.getCustomer();
            // 添加空指针保护
            if (customer == null) {
                return ResultData.failure("用户未登录");
            }

            if ((customer.getMemberStatus() == MEMBER_STATUS_TRUE && productType == PRODUCT_TYPE_SMS)
                    || (customer.getSmsExpireTime() != null
                    && customer.getSmsExpireTime().isAfter(LocalDateTime.now())
                    && productType == PRODUCT_TYPE_SMS)) {
                wrapper.in(Product::getProductType, PRODUCT_TYPE_SMS, PRODUCT_TYPE_SMS_ADDITION);
            } else {
                wrapper.eq(Product::getProductType, productType);
            }

            wrapper.orderByAsc(Product::getProductType)
                    .orderByAsc(Product::getMonthSmsQuantity);
            wrapper.eq(Product::getValidFlag, NUMBER_1);
        } else {
            wrapper.orderByDesc(Product::getCreateTime);
        }

        // 在构建完所有条件后执行查询
        List<Product> productList = list(wrapper);

        // 费用替换逻辑（保持原有逻辑）
        if (productType != null) {
            Customer customer = SaTokenUtilPy.getCustomer();
            if (customer != null && customer.getMemberStatus() != MEMBER_STATUS_TRUE) {
                productList.forEach(p -> p.setFee(p.getCommonFee()));
            }
        }


        return ResultData.successData(productList);
    }

    /**
     * 删除套餐
     */
    @Override
    public ResultData del(Integer productId) {
        Product product = getById(productId);
        if (product == null) {
            return ResultData.failure("套餐不存在");
        }
        return product.deleteById() ? ResultData.successMsg("删除成功") : ResultData.failure("删除失败");
    }
    /**修改套餐启用状态*/
    @Override
    public ResultData updateStatus(updateStatusModel model) {
        SysUser sysUser = SaTokenUtilPy.getSysUser();
        Product product = getById(model.getProductId());
        if (product == null){
            return ResultData.failure("套餐不存在");
        }
        BeanUtils.copyProperties(model, product);
        product.setUpdateTime(LocalDateTime.now());
        product.setUpdaterId(sysUser.getUserId());
        return updateById(product) ?
                ResultData.successMsg("修改成功") :
                ResultData.failure("修改失败");
    }
}
